#pragma once 

#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
using namespace std;

//设计方的视角

//typedef function<void()> func_t
using func_t = function<void()>; 

class Thread
{
public:
    Thread(func_t func, const string& threadname)
        :_tid(0)
        ,_threadname(threadname)
        ,_isrunning(false)
        ,_func(func)
    {}

    //改为static, 参数就没有this指针了!
    static void* ThreadRoutine(void* args) //不加static, 类内方法, 默认携带this指针
    {
        Thread* ts = static_cast<Thread *>(args);
        ts->_func();
        return nullptr;   
    }

    bool start()
    {
        int n = pthread_create(&_tid, nullptr, ThreadRoutine, this);
        if(n == 0) 
        {
            _isrunning  = true;
            return true;
        }
        else 
        {
            return false;
        }
    }

    bool join()
    {
        if(!_isrunning) return true;
        int n = pthread_join(_tid, nullptr);
        if(n == 0)
        {
            _isrunning = false;
            return true;
        }
        else
        {
            return false;
        }
    }

    string ThreadName()
    {
        return _threadname;
    }
    
    bool IsRunning()
    {
        return _isrunning;
    }

    ~Thread()
    {

    }
private:
    pthread_t _tid;
    string  _threadname;
    bool _isrunning;
    func_t _func; //回调函数
};